package com.yj.generator.core;

import com.yj.generator.constants.ConfigConstant;
import com.yj.generator.entity.GenerateOut;
import com.yj.generator.entity.Table;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * @title 实体类生成
 * @author DengLin
 * @date 2024/07/15
 */
public class BeanGenerateFileImpl implements GenerateFile {

    private static final Logger log = LogManager.getLogger(BeanGenerateFileImpl.class);

    @Override
    public void generate(GenerateOut generateOut, Map<String, Object> model) {
        String projectPath= generateOut.getOutPath();
        String outPackage = generateOut.getOutPackage();
        String fileFoldName = generateOut.getOutEntity();
        model.put("module",fileFoldName);
        String outPackagePath = outPackage.replaceAll("\\.", Matcher.quoteReplacement("\\"));
        String targetPath = projectPath + ConfigConstant.JAVA_FILE_PATH +outPackagePath + File.separator + fileFoldName;
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            if (!targetFile.mkdirs()) {
                log.error("目标生成文件夹创建失败————路径为:{}",targetFile.getAbsolutePath());
            }
        }

        Writer writer = null;
        Table table = (Table) model.get("table");
        try {
            writer = new FileWriter(new File(targetFile,table.getBeanName()+".java"));
            Template template = configuration.getTemplate("bean.ftl");
            template.process(model, writer);
        } catch (Exception e) {
            log.error("实体文件生成失败:{}", e.getMessage());
        }finally {
            if (writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error("文件流关闭异常:{}",e.getMessage());
                }
                log.info("{}生成成功",table.getBeanName()+"Bean");
            }
        }
    }
}
